﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;

namespace CLEX.Service.DataContracts
{
    [DataContract]
    public class SchemaData
    {
        private static readonly IEqualityComparer<SchemaData> valueComparer = new SchemaDataValueComparer();
        [DataMember]
        private readonly List<TableData> tables;
        private ReadOnlyCollection<TableData> tablesReadonly;

        public static IEqualityComparer<SchemaData> ValueComparer
        {
            get { return SchemaData.valueComparer; }
        } 

        public ReadOnlyCollection<TableData> Tables
        {
            get
            {
                if (tablesReadonly == null)
                {
                    tablesReadonly = new ReadOnlyCollection<TableData>(this.tables);
                }
                return tablesReadonly;
            }
        }

        private SchemaData()
        {

        }

        public SchemaData(IEnumerable<TableData> tables)
        {
            this.tables = tables.ToList();
            this.tablesReadonly = new ReadOnlyCollection<TableData>(this.tables);
        }

        public override string ToString()
        {
            return string.Format("Tables: {0}", Tables);
        }

        private sealed class SchemaDataValueComparer : IEqualityComparer<SchemaData>
        {
            public bool Equals(SchemaData x, SchemaData y)
            {
                if (Object.ReferenceEquals(x, y))
                {
                    return true;
                }
                if (Object.ReferenceEquals(x, null))
                {
                    return false;
                }
                if (Object.ReferenceEquals(y, null))
                {
                    return false;
                }

                return x.tables.SequenceEqual(y.tables, TableData.ValueComparer);
            }

            public int GetHashCode(SchemaData obj)
            {
                if (obj == null)
                {
                    return 0;
                }
                else
                {
                    int hash = 0;
                    foreach (TableData table in obj.tables)
                    {
                        hash ^= TableData.ValueComparer.GetHashCode(table);
                    }
                    return hash;
                }
            }
        }
    }
}
